package com.androidtestintent2.handlerm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {
    private ProgressBar bar=null;
    private Button button=null;
    private boolean bon=true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button stop=(Button)findViewById(R.id.button2);
        stop.setOnClickListener(new stop());
        bar=(ProgressBar)findViewById(R.id.progressBar);
        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new buttonlistener());
    }

    //没到100前可以手动停止线程
    private class stop implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            bon=false;
        }
    }
    private class buttonlistener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            bon=true;//手动停止后可以手动继续运行，到100也可以重新开始，不过我不知道进度条怎么弄。
            bar.setVisibility(View.VISIBLE);
            updateBarHandler.post(runnable);

        }
    }
    Handler updateBarHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            bar.setProgress(msg.arg1);
            updateBarHandler.post(runnable);
        }

    };
    Runnable runnable=new Runnable() {
        int i=0;
        @Override
        public void run() {
            if(bon) {
                Toast.makeText(MainActivity.this, "开始线程", Toast.LENGTH_SHORT).show();
                i = i + 10;
                Message msg = updateBarHandler.obtainMessage();
                msg.arg1 = i;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                updateBarHandler.sendMessage(msg);
                //到100时自动停止
                if(i==100){
                    bon=false;
                }
            }
        }
    };
}

